import { lstat, readdir, readFile, readlink, realpath, stat } from 'fs/promises'
import type { InputFileSystem } from './types'

export const commonInputFS: InputFileSystem = {
  readFile,
  readlink,
  readdir: path => readdir(path, { withFileTypes: true }),
  stat: async fileName => {
    try {
      return await stat(fileName)
    } catch {}
  },
  lstat: async fileName => {
    try {
      return await lstat(fileName)
    } catch {}
  },
  realpath: realpath
}

export const placeholderPrefix = '__COMPLUGIN_ASSET__'
export const placeholderSuffix = '__'
export const placeholderRegexp = new RegExp(`^${placeholderPrefix}\\w+${placeholderSuffix}$`)
export const placeholderMatchRegexp = new RegExp(
  `^(?<k>['"]?)${placeholderPrefix}(?<ref>\\w+)${placeholderSuffix}\\k<k>$`
)
export const placeholderGlobalMatchRegexp = new RegExp(
  `(?<k>['"]?)\\b${placeholderPrefix}(?<ref>\\w+)${placeholderSuffix}\\b\\k<k>`,
  'g'
)
